package com.group.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group.entity.user.UserAccountEntity;
import com.group.entity.wms.ClassifyEntity;
import com.group.entity.wms.GoodsEntity;
import com.group.entity.wms.PositionEntity;
import com.group.entity.wms.SupplierEntity;
import com.group.exception.IndustryException;
import com.group.mapper.ClassifyMapper;
import com.group.mapper.GoodsMapper;
import com.group.mapper.PositionMapper;
import com.group.mapper.SupplierMapper;
import com.group.mapper.UserAccountMapper;
import com.group.service.GoodsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, GoodsEntity> implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private UserAccountMapper userAccountMapper;
    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private ClassifyMapper classifyMapper;
    @Resource
    private PositionMapper positionMapper;
    @Override
    public Page<GoodsEntity> findAll(Integer page, Integer size) {

        Page<GoodsEntity> pages  = new Page<>(page,size);

        List<GoodsEntity> all = this.goodsMapper.findAll(page-1, size);
        pages.setRecords(all);
        pages.setTotal(this.baseMapper.getTotalCount());
        //填充数据
        this.fillData(pages);
        return pages;
    }

    @Override
    public Page<GoodsEntity> findByCondition(GoodsEntity goodsEntity, Integer page, Integer size) {
        //查询与该表相关的信息，填充数据信息
        QueryWrapper<GoodsEntity> queryWrapper = this.initQueryWrapper(goodsEntity);
        List<SupplierEntity> supplierEntities = this.supplierMapper.selectList(null);
        List<UserAccountEntity> userAccountEntities = this.userAccountMapper.selectList(null);
        List<ClassifyEntity> list = this.classifyMapper.selectList(null);
        Map<Long, String> supplierNameMap = supplierEntities.stream().collect(Collectors.toMap(item -> item.getId(), item -> item.getSupplierName()));
        Map<Long, String> classifyNameMap = list.stream().collect(Collectors.toMap(item -> item.getId(), item -> item.getClassifyName()));
        Map<Long, String> userNameMap = userAccountEntities.stream().collect(Collectors.toMap(item -> item.getId(), item -> item.getUserName()));
        Page<GoodsEntity> pages = new Page<>(page,size);
        Page<GoodsEntity> goodsEntityPage = this.baseMapper.selectPage(pages, queryWrapper);
        for (GoodsEntity record : goodsEntityPage.getRecords()) {
            if (record.getCreateUser()!=null) record.setCreateUserName(userNameMap.get(record.getCreateUser()));
            if (record.getLastUpdateUser()!=null) record.setLastUpdateUserName(userNameMap.get(record.getLastUpdateUser()));
            if (record.getGoodsType()!=null) record.setGoodsTypeName(classifyNameMap.get(record.getGoodsType()));
            if (record.getSupplier()!=null) record.setSupplierName(supplierNameMap.get(record.getSupplier()));
        }
        return goodsEntityPage;
    }

    /**
     * 根据储位id查找
     * @param positionId
     * @return
     */
    @Override
    public Page<GoodsEntity> findByPosition(Long positionId,Integer page,Integer size) {
        if (page==null||page==0) page=1;
        if (size==null||size==0) size=9;
        List<GoodsEntity> byPosition = this.baseMapper.findByPosition(positionId, page - 1, size);
        Page<GoodsEntity> pages = new Page<>(page,size);
        pages.setRecords(byPosition);
        pages.setTotal(this.baseMapper.getTotalCount());
        return pages;
    }

    @Override
    @Transactional
    public Integer add(GoodsEntity goodsEntity) {
        //添加商品信息
        goodsEntity.setCreateUser(1024L);
        goodsEntity.setCreateTime(new Date());
        goodsEntity.setCount(new BigDecimal(0));
        goodsEntity.setUseCount(new BigDecimal(0));
        goodsEntity.setLine(0);
        boolean save = this.save(goodsEntity);
        return save?1:0;
    }

    @Override
    @Transactional
    public Integer update(GoodsEntity goodsEntity) {
        return null;
    }

    @Override
    @Transactional
    public Integer delete(List<Long> ids) {
        List<GoodsEntity> goodsEntityList = this.baseMapper.selectBatchIds(ids);
        if (goodsEntityList==null||goodsEntityList.size()<ids.size()) throw new IndustryException("不存在的商品信息");
        //查看当前货品状态是否支持删除
        List<Long> goodsStateList = goodsEntityList.stream().filter(item -> item.getLine() == 2&&item.getStatus()==0).map(item -> item.getId()).collect(Collectors.toList());
        if (goodsStateList!=null&&goodsStateList.size()>=1) throw new IndustryException("商品已经在使用无法删除");
        //删除禁用的商品信息
        //查找商品储位信息
        List<Long> positionIds = goodsEntityList.stream().map(item -> item.getPositionId()).collect(Collectors.toList());

        //查找储位信息
        List<PositionEntity> positionEntities = this.positionMapper.selectBatchIds(positionIds);
        Map<Long, PositionEntity> positionMap = positionEntities.stream().collect(Collectors.toMap(item -> item.getId(), item -> item));
        //扣减储位库存

        for (GoodsEntity goodsEntity : goodsEntityList) {
            BigDecimal count = goodsEntity.getCount();
            PositionEntity positionEntity = positionMap.get(goodsEntity.getPositionId());
            if (positionEntity!=null)
            positionEntity.setStorageCount(positionEntity.getStorageCount().subtract(count));

        }
        //更新库存
        positionMap.forEach((key,value)->{
            this.positionMapper.updateById(value);
        });

        return this.baseMapper.deleteBatchIds(ids);

    }

    @Override
    public GoodsEntity findById(Long goodsId) {
        return this.baseMapper.findById(goodsId);
    }

    /**
     * 填充数据
     * @param page
     */
    @Override
    public void fillData(Page<GoodsEntity> page) {
        List<UserAccountEntity> userAccountEntities = this.userAccountMapper.selectList(null);
        Map<Long, String> userNameMap = userAccountEntities.stream().collect(Collectors.toMap(item -> item.getId(), item -> item.getUserName()));
        for (GoodsEntity goodsEntity : page.getRecords()) {
            goodsEntity.setLastUpdateUserName(userNameMap.get(goodsEntity.getLastUpdateUser()));
        }
    }

    /**
     * 填充数据
     * @param goodsEntity
     */
    public void fillData(GoodsEntity goodsEntity){
        List<UserAccountEntity> userAccountEntities = this.userAccountMapper.selectList(null);
        Map<Long, String> userNameMap = userAccountEntities.stream().collect(Collectors.toMap(item -> item.getId(), item -> item.getUserName()));
        goodsEntity.setLastUpdateUserName(userNameMap.get(goodsEntity.getLastUpdateUser()));
    }

    /**
     * 根据名称查找
     * @param keyWorld
     * @return
     */
    @Override
    public List<GoodsEntity> findByNameLike(String keyWorld) {
        return this.baseMapper.findByGoodsNameLike(keyWorld);
    }

    /**
     * 生成查询条件
     * @param goodsEntity
     * @return
     */
    @Override
    public QueryWrapper<GoodsEntity> initQueryWrapper(GoodsEntity goodsEntity) {
        QueryWrapper<GoodsEntity> queryWrapper = new QueryWrapper<>();
        if (goodsEntity.getGoodsName()!=null && goodsEntity.getGoodsName().length()>0){
            queryWrapper.eq("goods_name",goodsEntity.getGoodsName());
        }
        else if (goodsEntity.getGoodsType()!=null){
            queryWrapper.eq("goods_type",goodsEntity.getGoodsType());
        }
        else if (goodsEntity.getCreateUser()!=null){
            queryWrapper.eq("create_user",goodsEntity.getCreateUser());
        }
        else if (goodsEntity.getIsPiece()!=null){
            queryWrapper.eq("is_piece",goodsEntity.getIsPiece());
        }
        else if (goodsEntity.getIsWeight()!=null){
            queryWrapper.eq("is_weight",goodsEntity.getIsWeight());
        }
        else if (goodsEntity.getSupplier()!=null){
            queryWrapper.eq("supplier",goodsEntity.getSupplier());
        }
        else if (goodsEntity.getUnit()!=null&&goodsEntity.getUnit().length()>=1){
            queryWrapper.eq("unit",goodsEntity.getUnit());
        }
        else if (goodsEntity.getStatus()!=null){
            queryWrapper.eq("status",goodsEntity.getStatus());
        }
        else if (goodsEntity.getLastUpdateUser()!=null){
            queryWrapper.eq("last_update_user",goodsEntity.getLastUpdateUser());
        }
        else if (goodsEntity.getBeginCreateTime()!=null){
            queryWrapper.ge("create_time",goodsEntity.getBeginCreateTime());
        }
        else if (goodsEntity.getEndCreateTime()!=null){
            queryWrapper.le("create_time",goodsEntity.getCreateTime());
        }

        return queryWrapper;
    }
}
